package com.alex.seo.context;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.springframework.context.support.AbstractXmlApplicationContext;

public class SeoApplicationContext extends AbstractXmlApplicationContext {

	public SeoApplicationContext() {
		String[] configLocations = findConfigLocations();
		setConfigLocations(configLocations);
		refresh();
	}

	private String[] findConfigLocations() {
		String classpath = System.getProperty("java.class.path");
		String[] classpathEntries = classpath.split(File.pathSeparator);

		Collection<String> res = new ArrayList<String>();
		for (String classpathEntry : classpathEntries) {
			if (classpathEntry.endsWith(".jar")) {
				findJarConfigLocations(classpathEntry, res);
			} else {
				findConfigLocations(classpathEntry, res);
			}
		}
		return res.toArray(new String[0]);
	}

	private void findConfigLocations(String classpathEntry, Collection<String> res) {
		File dir = new File(classpathEntry);
		Collection<File> files = FileUtils.listFiles(dir, new String[] { "xml" }, true);
		
		for (File file : files) {
			String relativePath = file.toString().substring(classpathEntry.length());
			if (relativePath.startsWith("/spring")) {
				res.add(relativePath);
			}
		}
	}

	private void findJarConfigLocations(String jar, Collection<String> res) {
		Pattern pattern = Pattern.compile("spring/[^\\.]+\\.xml$");
		try {
			JarFile jarFile = new JarFile(jar);
			Enumeration<JarEntry> entries = jarFile.entries();
			while (entries.hasMoreElements()) {
				JarEntry entry = entries.nextElement();
				if (pattern.matcher(entry.getName()).matches()) {
					res.add(entry.getName());
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}